<template>
  <div id="hitch_order_form">
    <top-bar></top-bar>
    <div class="container">
      <div class="field_box with_shadow">
        <md-field>
          <md-input-item
            :value="startInfo?startInfo.address.stationName:''"
            class="no-right-padding"
            ref="startLocation"
            :placeholder="'从哪出发'"
            readonly
            @click.native="selectStart"
          >
            <svg fill="#3F88EB" width="12" height="12" slot="left">
              <circle cx="6" cy="6" r="3" />
            </svg>
          </md-input-item>
          <md-input-item
            :value="endInfo?endInfo.address.stationName:''"
            class="no-right-padding"
            ref="endLocation"
            :placeholder="'您要去哪'"
            readonly
            @click.native="selectEnd"
          >
            <svg fill="#FF6917" width="12" height="12" slot="left">
              <circle cx="6" cy="6" r="3" />
            </svg>
          </md-input-item>
          <md-field-item :customized="true">
            <md-input-item
              class="inline_field"
              :value="timeInfo?timeInfo.type=='1'?'随时可走':timeInfo.text:''"
              ref="startTime"
              placeholder="选择用车时间"
              readonly
              slot="left"
              @click.native="selectStartTime"
            >
              <md-icon class="place_icon" name="time" slot="left"></md-icon>
            </md-input-item>
            <md-input-item
              class="inline_field"
              ref="numSelector"
              placeholder="选择乘车人数"
              readonly
              slot="right"
              :value="numberText"
              @click.native="selectPassenegerNum"
            >
              <md-icon class="place_icon" name="pc_pcrs" slot="left"></md-icon>
            </md-input-item>
          </md-field-item>
          <md-field-item :customized="true">
            <md-input-item
              class="inline_field"
              ref="remarks"
              placeholder="出行备注"
              readonly
              slot="left"
              :value="selectedRemarks.length>0?'已添加':''"
              @click.native="selectRemark"
            >
              <md-icon class="place_icon" name="chuxingbeizhu" slot="left"></md-icon>
            </md-input-item>
            <md-input-item
              class="inline_field"
              ref="reward"
              placeholder="感谢费"
              readonly
              :value="rewardText"
              @click.native="selectReward"
            >
              <md-icon class="place_icon" name="hongbao_icon" slot="left"></md-icon>
            </md-input-item>
          </md-field-item>
        </md-field>
      </div>
      <div class="cost_box with_shadow" v-if="costInfo">
        <div class="cost-info" v-if="numberInfo.isPinche">
          <div class="tishi-line row centered">
            拼车成功
            <span>
              <md-icon class="tishi-icon" name="xc_question" @click="showTishi"></md-icon>
            </span>
          </div>
          <div class="row centered">
            <div class="price">
              <span class="symbol">￥</span>
              {{ costInfo.pinAmt }}
              <span class="symbol">起</span>
            </div>
            <md-icon class="more-icon" name="wdqb-more" @click="gotoCostDetail"></md-icon>
          </div>
          <div class="desc" v-if="true">未拼成独享价{{ costInfo.baoAmt }}元</div>
        </div>
        <div class="cost-info" v-if="!numberInfo.isPinche">
          <div class="tishi-line row centered">独享价</div>
          <div class="row centered">
            <div class="price">
              <span class="symbol">￥</span>
              {{ costInfo.pinAmt }}
            </div>
            <md-icon class="more-icon" name="wdqb-more" @click="gotoCostDetail"></md-icon>
          </div>
        </div>
      </div>
      <md-button class="submit-btn" @click="submitOrder" :disabled="!costInfo">提交订单</md-button>
    </div>
  </div>
</template>
<script>
import '@/assets/svgs/shangchedian.svg';
import '@/assets/svgs/xiachedian.svg';
import '@/assets/svgs/time.svg';
import '@/assets/svgs/pc_pcrs.svg';
import '@/assets/svgs/chuxingbeizhu.svg';
import '@/assets/svgs/right_arrow.svg';
import '@/assets/svgs/tk_close.svg';
import '@/assets/svgs/wdqb-more.svg';
import '@/assets/svgs/xc_question.svg';
import '@/assets/svgs/hongbao_icon.svg';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import TopBar from '@/components/TopBar';
import Popup from './popup';
import { Field, FieldItem, Icon, InputItem, Button, Dialog } from 'mand-mobile';
import { createNamespacedHelpers } from 'vuex';
import Loading from '@/components/loading';
import Utils from '@/common/pakjUtils';
const { mapState, mapActions, mapGetters, mapMutations } = createNamespacedHelpers('hitchhike');
export default {
  name: 'hitch-order-form',
  components: {
    [Field.name]: Field,
    [FieldItem.name]: FieldItem,
    [Icon.name]: Icon,
    [InputItem.name]: InputItem,
    [Button.name]: Button,
    TopBar
  },
  data() {
    return {
      startInfo: null,
      endInfo: null,
      timeInfo: null,
      numberInfo: null,
      selectedRemarks: [],
      rewardInfo: null
    };
  },
  created() {
    if (this.$route.params) {
      if (this.$route.params.start) {
        this.startInfo = this.$route.params.start;
      }
      if (this.$route.params.end) {
        this.endInfo = this.$route.params.end;
      }
      if (this.$route.params.type) {
        if (this.$route.params.type === 'work') {
          // 提取去上班信息
          this.startInfo = this.gotoWorkInfo.startInfo;
          this.endInfo = this.gotoWorkInfo.endInfo;
          this.timeInfo = this.gotoWorkInfo.timeInfo;
          this.numberInfo = this.gotoWorkInfo.numberInfo;
        } else if (this.$route.params.type === 'home') {
          // 提取回家信息
          this.startInfo = this.gotoHomeInfo.startInfo;
          this.endInfo = this.gotoHomeInfo.endInfo;
          this.timeInfo = this.gotoHomeInfo.timeInfo;
          this.numberInfo = this.gotoHomeInfo.numberInfo;
        }
        this.checkForm();
      }
    }
  },
  methods: {
    ...mapActions(['getTimePickerData', 'getCostInfo', 'createOrder']),
    async selectStart() {
      try {
        this.startInfo = await Popup.selectStartPosition();
        this.checkForm();
      } catch (reason) {
        console.log(reason);
      }
    },
    async selectEnd() {
      try {
        this.endInfo = await Popup.selectEndPosition();
        this.checkForm();
      } catch (reason) {
        console.log(reason);
      }
    },
    async selectStartTime() {
      if (this.hasStartInfo()) {
        Loading.show();
        await this.getTimePickerData(this.startInfo.city.cityId);
        Loading.hide();
        try {
          this.timeInfo = await Popup.selectTime({
            pickerData: this.timePickerData,
            cityInfo: this.startInfo.city
          });
          this.checkForm();
        } catch (reason) {
          console.log(reason);
        }
      }
    },
    async selectPassenegerNum() {
      if (this.hasStartInfo()) {
        try {
          this.numberInfo = await Popup.selectNumber(this.startInfo.city.pinOpenFlag);
          this.checkForm();
        } catch (reason) {
          console.log(reason);
        }
      }
    },
    async selectRemark() {
      if (this.hasStartInfo()) {
        try {
          this.selectedRemarks = await Popup.selectRemark(this.startInfo.city);
        } catch (reason) {
          console.log(reason);
        }
      }
    },
    async selectReward() {
      try {
        this.rewardInfo = await Popup.selectReward();
        this.checkForm();
      } catch (reason) {
        console.log(reason);
      }
    },
    async readyCostInfoParams() {
      let startLnglat = encryptByDESModeEBC(this.coordToString(this.startInfo.address.coordinate));
      let destLnglat = encryptByDESModeEBC(this.coordToString(this.endInfo.address.coordinate));
      let params = {
        cityId: this.startInfo.city.cityId, // 城市ID
        originLngLat: startLnglat, // 起点坐标（加密）
        destLngLat: destLnglat, // 终点坐标（加密）
        timeType: this.timeInfo.type, // 时间类型 1： 随时可走； 2： 预约
        orderTime: this.timeInfo.time.toString(), // 预约时间（毫秒时间戳）
        orderNum: encryptByDESModeEBC(this.numberInfo.number.toString()), // 乘车人数
        orderType: this.numberInfo.isPinche ? '1' : '0', // 是否拼车 0： 独享；1： 拼车
        orderRedMoney: encryptByDESModeEBC(
          this.rewardInfo ? this.rewardInfo.toString() : undefined
        ), // 红包金额
        timeSpan: this.startInfo.city.orderAutoTime
      };
      await this.getCostInfo(params);
    },
    gotoCostDetail() {},
    showTishi() {
      console.log('打开提示');
    },
    async submitOrder() {
      let startLnglat = encryptByDESModeEBC(this.coordToString(this.startInfo.address.coordinate));
      let destLnglat = encryptByDESModeEBC(this.coordToString(this.endInfo.address.coordinate));
      let params = {
        cityId: this.startInfo.city.cityId, // 城市ID
        originLngLat: startLnglat, // 起点坐标（加密）
        originShortAddress: this.startInfo.address.stationName,
        originLongAddress: this.startInfo.address.position,
        destLngLat: destLnglat, // 终点坐标（加密）
        destShortAddress: this.endInfo.address.stationName,
        destLongAddress: this.endInfo.address.position,
        timeType: this.timeInfo.type, // 时间类型 1： 随时可走； 2： 预约
        orderTime: this.timeInfo.time.toString(), // 预约时间（毫秒时间戳）
        orderNum: encryptByDESModeEBC(this.numberInfo.number.toString()), // 乘车人数
        orderAmt: encryptByDESModeEBC(
          this.numberInfo.isPinche ? this.costInfo.pinAmt : this.costInfo.baoAmt
        ),
        orderType: this.numberInfo.isPinche ? '1' : '0', // 是否拼车 0： 独享；1： 拼车
        orderRedMoney: encryptByDESModeEBC(
          this.rewardInfo ? this.rewardInfo.toString() : undefined
        ), // 红包金额
        timeSpan: this.startInfo.city.orderAutoTime,
        remarks: this.selectedRemarks.join(';'),
        source: Utils.getCurrentEnvEnum()
      };
      await this.createOrder(params);
      if (this.orderInfo) {
        this.$router.replace({
          name: 'HitchWaitingLobby',
          query: {
            orderno: this.orderInfo.orderNo
          }
        });
      }
    },
    hasStartInfo() {
      if (!this.startInfo) {
        Dialog.alert({
          title: '错误',
          content: '请选择起点以及终点'
        });
        return false;
      } else {
        return true;
      }
    },
    coordToString(coordinate) {
      return coordinate[0] + ',' + coordinate[1];
    },
    checkForm() {
      if (this.startInfo && this.endInfo && this.timeInfo && this.numberInfo) {
        this.readyCostInfoParams();
      }
    }
  },
  computed: {
    ...mapGetters(['timePickerData', 'costInfo', 'orderInfo', 'gotoHomeInfo', 'gotoWorkInfo']),
    rewardText() {
      if (this.rewardInfo) {
        return '感谢费' + this.rewardInfo + '元';
      } else {
        return '';
      }
    },
    numberText() {
      if (this.numberInfo) {
        const typeString = this.numberInfo.isPinche ? '拼车' : '独享';
        return this.numberInfo.number + '人' + typeString;
      } else {
        return '';
      }
    }
  }
};
</script>
<style lang="stylus">
#hitch_order_form {
  height: 100vh;
  background-color: color-primary-background;

  .container {
    padding: 20px;
    box-sizing: border-box;

    .field_box {
      background-color: #fff;
      border-radius: 10px;
      padding: 5px;

      .no-right-padding {
        padding-right: 20px;
      }

      .field_item {
        height: 88px;
        font-size: 28px;
      }

      .place_icon {
        width: 20px;
        height: 20px;
      }

      .inline_field {
        padding: 0px;
      }

      .md-field-item {
        .md-field-item-inner {
          padding-top: 0px;
          padding-bottom: 0px;
        }
      }

      .md-input-item-right {
        width: 250px;
        justify-content: flex-end;
      }
    }

    .cost_box {
      margin-top: 20px;
      background-color: #fff;
      border-radius: 10px;
      padding: 5px;

      .cost-info {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        height: 260px;
        box-sizing: border-box;

        .tishi-line {
          font-size: 28px;
          color: #333333;
          line-height: 28px;
          vertical-align: middle;
          box-sizing: border-box;

          .tishi-icon {
            width: 28px;
            height: 28px;
            margin-left: 10px;
          }
        }

        .price {
          font-size: 48px;
          text-align: center;
          font-weight: bold;
          margin: 20px 10px;

          .symbol {
            font-size: 28px;
            font-weight: normal;
          }

          .more-icon {
            width: 16px;
            height: 26px;
          }
        }

        .desc {
          width: 283px;
          height: 34px;
          font-size: 24px;
          text-align: center;
          width: 100%;
          color: color-text-caption;
        }
      }
    }

    .submit-btn {
      margin-top: 20px;
    }
  }
}
</style>
